package ebcs.scan.controller.contractCtr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import ebcs.database.bean.BsContractInfor;
import ebcs.database.bean.ProjectCostInfo;
import ebcs.database.bean.RpProjectMoneyBean;
import ebcs.database.service.BsContractInforServiceImp;
import ebcs.scan.bean.common.ExcleEntity;
import ebcs.scan.common.utils.ExportDataUtil;
import ebcs.scan.common.utils.StringUtil;
import jplat.core.trans.JAppBaseService;
import jplat.core.trans.JAppContext;
import jplat.core.trans.JAppContextFactory;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;
import jplat.tools.string.DateUtil;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

@Controller
public class BsContractInforCtrl extends JAppBaseService {
	
	private Logger logger = Logger.getLogger(BsContractInforCtrl.class);

	protected JAppContextFactory serviceFactory = new JAppContextFactory();
	
	@Autowired
	public BsContractInforServiceImp bsContractInforServiceImp;
	
	/**
	 * 上传合同号、产品编号excel
	 */
	@RequestMapping("/page/contract/importContractExcel.do")
	@ResponseBody
	public void importContractExcel(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "excelFile", required = true) MultipartFile  excelFile)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextNoUser(request, response);// 自动客户信息
		List<BsContractInfor> list = new ArrayList<>(); 
		try {
			Workbook wb = Workbook.getWorkbook(excelFile .getInputStream());
			// 获取选项卡对象 第0个选项卡  
	        Sheet sheet = wb.getSheet(0);  
	        int colNum = sheet.getRow(0).length;//获取Excel列数
	        int rows = sheet.getRows();
	        //从第三行开始遍历
	        Pattern pattern = Pattern.compile("\\d{6}");
	        int flag=0;
	        for (int i = 2; i < rows; i++) {
                for (int j = 1; j < 3; j++) {
                    //第一个是列数，第二个是行数
                	String contractId=sheet.getCell(j++, i).getContents();
                	String contractNo=sheet.getCell(j++, i).getContents();
                    
                    if(StringUtil.isEmpty(contractId) || StringUtil.isEmpty(contractNo)){
                    	flag=1;
        	        	break;
                    }
                    if(StringUtil.isNotEmpty(contractId) && StringUtil.isNotEmpty(contractNo)){
                    	BsContractInfor bsContractInfor = new BsContractInfor();
                    	String rouid = UUID.randomUUID().toString().replace("-", "");
                    	bsContractInfor.setRouid(rouid);
                    	bsContractInfor.setContractId(contractId);
                    	bsContractInfor.setContractNo(contractNo);
                        list.add(bsContractInfor);
                    }
                }
                if(flag==1){
                	break;
                }
            }
	        //list为空,说明Excel没数据
	        if(list==null||list.size()<=0){
	        	context.buildAppResponse("FALSE3");
	        	return;
	        }
	       //遍历查询是否有数据重复
			List<BsContractInfor> rsList = bsContractInforServiceImp.searchContractInfor();
			if(rsList!=null&&rsList.size()>0){
				for (BsContractInfor p1 : rsList) {
					if(StringUtil.isNotEmpty(p1.getContractId())&&StringUtil.isNotEmpty(p1.getContractNo())){
					for (BsContractInfor p2 : list) {
						if(StringUtil.isNotEmpty(p2.getContractId())&&StringUtil.isNotEmpty(p2.getContractNo())){
							if(p1.getContractId().equals(p2.getContractId()) && p1.getContractNo().equals(p2.getContractNo())){
								context.buildAppResponse("FALSE5");
					        	return;
							}
						}
					}
				  }
				}
			}
	        //将得到的数据批量插入数据库
			bsContractInforServiceImp.insertContractInfor(list);
	        context.buildAppResponse("OK");
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			context.buildAppResponse("FALSE6");
        	return;
		}  catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
	}
	
	/**
	 * 查询合同单信息
	 */
	@RequestMapping("/page/contract/searchContractInfor.do")
	public void searchContractInfor(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextNoUser(request, response);// 自动客户信息
		BsContractInfor req = context.obtainReqModel(BsContractInfor.class);
		req.setEndRow((Integer.parseInt(req.getStartRow()))+(Integer.parseInt(req.getPageSize()))+"");
		List<BsContractInfor> rsList = bsContractInforServiceImp.searchContractInfors(req);
		int count = bsContractInforServiceImp.searchContractInforPageCount(req);
		Map rsModel = new HashMap();
		rsModel.put("count", count);
  		rsModel.put("rsList", rsList);
 		context.buildAppResponse(rsModel);
	}
	
	/**
	  * 合同单导入模板
	  */
	@RequestMapping("/page/contract/downContractExcelFile.do")
	public void doReportCountExcelFile(HttpServletRequest request, HttpServletResponse response)throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextNoUser(request, response);// 自动客户信息
       //查询人员信息
		List<BsContractInfor> rsList = new ArrayList<>();
		BsContractInfor bsContractInfor = new BsContractInfor();
		bsContractInfor.setContractId("01");
		bsContractInfor.setContractNo("001(示例,可删除)");
		rsList.add(bsContractInfor);
		String path = request.getServletContext().getRealPath("");// 获取项目动态绝对路径
		ExportDataUtil export = new ExportDataUtil();
		ExcleEntity entity = new ExcleEntity();
		entity.setTitle("合同单导入模板");
		entity.setFileName(DateUtil.getSystemTimeBySomeFormat(DateUtil.FMT_ALL) + ".xls");
		entity.setPath(path);
		Map<Object, String> headMap = new LinkedHashMap<Object, String>();
		headMap.put("contractId","合同号");
		headMap.put("contractNo","产品编号");
		
		entity.setHeadMap(headMap);
		export.exportExcel(entity, rsList);
		context.buildAppResponse(entity);
	}
	
	/**
	 * 删除合同单信息
	 */
	@RequestMapping("/page/contract/deleteContract.do")
    public void deleteRewardForm(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsContractInfor req = context.obtainReqModel(BsContractInfor.class);
        int i=bsContractInforServiceImp.deleteContract(req);
        if(i==0){
        	context.buildAppResponse("FALSE");
        }
        if(i==1){
        	context.buildAppResponse("OK");
        }
    }
	 
	@RequestMapping("/page/contract/selectContractIdByContractNo.do")
    public void selectContractIdByContractNo(HttpServletRequest request, HttpServletResponse response, String contractNo) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsContractInfor req = new BsContractInfor();
        req.setContractNo(contractNo);
        BsContractInfor bsContractInfor = bsContractInforServiceImp.selectContractIdByContractNo(req);
        String contractId = "";
        if(bsContractInfor != null) {
        	contractId = bsContractInfor.getContractId();
        }
        Map rspModel = new HashMap();
        rspModel.put("contractId", contractId);
        context.buildAppResponse(rspModel);
    }
}
